#include "MSqlServer.h"

using namespace NsMSql;

MSqlServer* MSqlServer::m_pInstance = NULL;

NsMSql::MSqlServer::MSqlServer()
{
    
}

MSqlServer& NsMSql::MSqlServer::getInstance()
{
    if (NULL == m_pInstance) 
    {
        m_pInstance = new MSqlServer();
    }

    return *m_pInstance;
}

bool NsMSql::MSqlServer::open(const MSqlServerAttr& sqlServerAttr)
{
    m_sqlServerAttr = sqlServerAttr;
    //打开服务器
    MSqlConnection sqlConnection(sqlServerAttr);
    m_open = sqlConnection.openServer();
    if (m_open)
    {
        //初始化数据库列表
        QString cmd = "show databases";
        QSqlQuery  query = sqlConnection.execWithRes(cmd, true);
        int columns = query.record().count();
        while (query.next())
        {
            QString name = query.value(0).toString();
            m_nameToDatabaseMap[name] = nullptr;
        }            
    }
    return m_open;
}

bool NsMSql::MSqlServer::isOpen()
{
    return m_open;
}

bool NsMSql::MSqlServer::createDatabase(const QString& databaseName)
{
    if (!m_open)
        return false;
	m_sqlServerAttr.databaseName = databaseName;
    //创建数据库
    MSqlConnection sqlConnection(m_sqlServerAttr);
    QString cmd = QString("CREATE DATABASE if not exists %1 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci").arg(databaseName);
    bool res = sqlConnection.execWithoutRes(cmd, true);;
	if (res && !m_nameToDatabaseMap.contains(databaseName))
	{
		m_nameToDatabaseMap[databaseName] = nullptr;
	}
	return res;
}

bool NsMSql::MSqlServer::dropDatabase(const QString& databaseName)
{
    if (m_nameToDatabaseMap.contains(databaseName))
    {
        if (m_currentDatabaseName == databaseName)     //当前数据库
        {
            MSqlError("database is using,cannt be drop");
            return false;
        }
        if (m_nameToDatabaseMap[databaseName]->drop());
        {
            delete m_nameToDatabaseMap[databaseName];
            m_nameToDatabaseMap[databaseName] = nullptr;
            m_nameToDatabaseMap.remove(databaseName);
            return true;
        }
    }
    return false;
}

MSqlDatabase* NsMSql::MSqlServer::useDatabase(const QString& databaseName)
{
    if (!m_open)
        return nullptr;
    if (m_nameToDatabaseMap.contains(databaseName))
    {
        if (m_nameToDatabaseMap[databaseName] == nullptr)
        {
            MSqlDatabase* pSqlDatabase = new MSqlDatabase(m_sqlServerAttr);
            m_nameToDatabaseMap[databaseName] = pSqlDatabase;
        }
        m_currentDatabaseName = databaseName;
        m_pCurrentDatabase = m_nameToDatabaseMap[databaseName];
        return m_pCurrentDatabase;
    }
    return nullptr;
}

QString NsMSql::MSqlServer::getCurrentDatabaseName()
{
    return m_currentDatabaseName;
}

QStringList NsMSql::MSqlServer::getDatabaseNameList()
{
    return m_nameToDatabaseMap.keys();
}
